<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="文章名称" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入文章名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['articles:article:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['articles:article:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['articles:article:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"   style="width: 100%" :data="tagsList" @selection-change="handleSelectionChange">
      <el-table-column width="60" align="center" type="selection" />
      <el-table-column width="170" align="center" label="文章封面">
        <template #default="scope">
          <el-image class="article-cover" :src="scope.row.avatar" />
          <i id="imgIcon" :class="scope.row.isSecret === 0 ? 'el-icon-view' : 'el-icon-lock'" />
        </template>
      </el-table-column>
      <el-table-column prop="title" align="center" label="文章名称" width="220">
        <template #default="scope">
          <el-link :underline="false" @click="onClick(scope.row)">{{ scope.row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" width="120" align="center" label="文章作者" />
      <el-table-column align="center" width="116" label="类型">
        <template #default="scope">
          <el-tag :type="scope.row.isOriginal === 0 ? 'warning' : 'success'" :key="index"
                  v-show="scope.row.isOriginal === index" v-for="(item, index) in isOriginalList">{{ item }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="125" label="分类">
        <template #default="scope">
          <el-tag style="margin-left: 3px" align="center" type="warning">{{ scope.row.categoryName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="220" label="标签">
        <template #default="scope">
          <el-tag style="margin-left: 3px" align="center" type="primary"
                  v-for="(item) in strSplit(scope.row.tagNames)">{{ item }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="canTop" prop="isStick" align="center" width="120" label="置顶">
        <template #default="scope">
          <el-switch v-model="scope.row.isStick" :active-value="1" :inactive-value="0" @change="handleTop(scope)"
                     active-color="#13ce66">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" label="阅读方式">
        <template #default="scope">
          <el-tag :type="readTypeStyle[scope.row.readType]">{{ readTypeList[scope.row.readType] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="120" label="状态">
        <template #default="scope">
          <el-tag v-for="(item, index) in publishList" :key="index" :type="item.listClass"  v-show="item.dictValue == scope.row.isPublish">
            {{ item.dictLabel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
      </el-table-column>
      <el-table-column width="250" fixed="right" align="center" label="操作">
        <template #default="scope">
          <el-button v-if="scope.row.isPublish == 1" type="info" size="mini" @click="offShelf(scope)">
            下架
          </el-button>
          <el-button type="primary"  size="mini"  @click="handleUpdate(scope.row)" v-hasPermi="['articles:article:edit']">编辑
          </el-button>
          <el-button type="danger"  size="mini"  @click="handleDelete(scope.row)" v-hasPermi="['articles:article:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改博客标签对话框 -->
    <el-dialog :title="title" v-model="open" center :fullscreen="fullscreenFlag">
      <el-form  ref="dataForm" :model="form" style="margin-top: 10px" :rules="rules">
        <el-row>
          <el-col :span="14">
            <el-form-item label="文章名称" :label-width="formLabelWidth" prop="title">
              <el-input v-model="form.title" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="文章简介" :label-width="formLabelWidth" prop="summary">
              <el-input auto-complete="off" v-model="form.summary"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标题图" :label-width="formLabelWidth">
              <el-col :span="2">
                <el-popover placement="top" width="160" trigger="hover" v-model:visible="visible">
                  <template #reference>
                    <el-icon class="icon-style">
                      <QuestionFilled/>
                    </el-icon>
                  </template>
                  <p>随机获取一张图片</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="small" type="text" @click="visible = false">取消</el-button>
                    <el-button type="primary" size="small" @click="randomImg">确定</el-button>
                  </div>
                </el-popover>
              </el-col>
              <el-col :span="2">
                <el-upload
                    name="file"
                    class="avatar-uploader"
                    :action="uploadImgUrl"
                    :on-success="handleUploadSuccess"
                    :on-remove="handleDeletePic"
                    :show-file-list="false">
                  <img v-if="form.avatar" :src="form.avatar" class="avatar"/>
                  <el-icon v-else class="avatar-uploader-icon ">
                    <Plus/>
                  </el-icon>
                </el-upload>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6.5">
            <el-form-item label="标签" :label-width="formLabelWidth" prop="tags">
              <el-tag v-for="(item, index) of form.tags" :key="index" style="margin:0 1rem 0 0" :closable="true"
                      @close="removeTag(item)">
                {{ item }}
              </el-tag>
              <el-popover placement="bottom-start" width="460" trigger="click" v-model:visible="isTagsValid">
                <template #reference>
                  <el-button type="primary" plain size="small">添加标签</el-button>
                </template>
                <div class="popover-title">标签</div>
                <!-- 搜索框 -->
                <el-input style="width:100%" v-model="tagName" placeholder="请输入标签名,enter添加自定义标签"
                          @keyup.enter.native="saveTag"/>
                <!-- 标签 -->
                <div class="popover-container">
                  <div>添加标签</div>
                  <el-tag v-for="(item, index) of tags" :key="index" style="margin-left: 3px;margin-top: 2px"
                          :class="tagClass(item)" @click="addTag(item)">
                    {{ item.name }}
                  </el-tag>
                </div>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item label="分类" :label-width="formLabelWidth" prop="categoryName">
              <el-tag type="success" v-show="form.categoryName" style="margin:0 1rem 0 0" :closable="true"
                      @close="removeCategory">
                {{ form.categoryName }}
              </el-tag>
              <!-- 分类选项 -->
              <el-popover placement="bottom-start" width="460" trigger="click" v-model:visible="isCategoryValid">
                <template #reference>
                  <el-button type="success" plain slot="reference" size="small">
                    添加分类
                  </el-button>
                </template>
                <div class="popover-title">分类</div>
                <!-- 输入框 -->
                <el-input style="width:100%" v-model="categoryName" placeholder="请输入分类名,enter添加自定义分类"
                          @keyup.enter.native="saveCategory"/>
                <!-- 分类 -->
                <div class="popover-container">
                  <div>添加分类</div>
                  <el-tag v-for="(item, index) of category" :key="index" style="margin-left: 3px;margin-top: 2px"
                          class="category-item" @click="addCategoryMethod(item)">
                    {{ item.name }}
                  </el-tag>
                </div>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item :label-width="formLabelWidth" label="是否置顶" prop="isStick">
              <el-radio-group v-model="form.isStick" size="small">
                <el-radio v-for="(item, index) in yesOrNoList" :label="index" border>{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6.5">
            <el-form-item :label-width="formLabelWidth" label="是否发布" prop="isPublish">
              <el-radio-group v-model="form.isPublish" size="small">
                <el-radio v-for="(item, index) in   publishList  " :key="item.dictValue"
                          :label="parseInt(item.dictValue)"
                          border>
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item :label-width="formLabelWidth" label="阅读方式" prop="readType">
              <el-select v-model="form.readType" placeholder="请选择阅读方式">
                <el-option v-for="(  item, index  ) in   readTypeList  " :key="index" :label="item" :value="index">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item :label-width="formLabelWidth" label="创作类型" prop="isOriginal">
              <el-radio-group v-model="form.isOriginal" size="small">
                <el-radio v-for="(  item, index  ) in   isOriginalList  " :label="index" border>{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.isOriginal === 0" :span="5">
            <el-form-item :label-width="formLabelWidth" label="原文链接" prop="originalUrl">
              <el-input v-model="form.originalUrl"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item :label-width="formLabelWidth" label="是否推荐" prop="isRecommend">
              <el-radio-group v-model="form.isRecommend" size="small">
                <el-radio v-for="(  item, index  ) in   yesOrNoList  " :label="index" border>{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item :label-width="formLabelWidth" label="是否首页轮播" prop="isCarousel">
              <el-radio-group v-model="form.isCarousel" size="small">
                <el-radio v-for="(  item, index  ) in   yesOrNoList  " :label="index" border>{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :spam="24">
            <el-form-item label="内容"   prop="contentMd">
              <MdEditor noUploadImg  v-model="form.contentMd" placeholder="输入文章内容..." style="height: 500px" ref=md   />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" style="margin-inline: 46%">确 定</el-button>
        <el-button @click="cancel" style="margin-inline: -45%">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script setup name="Tags">
import {listTags, getTags, addTags, updateTags, delTags, listNoPage} from "@/api/blog/tags";
import {computed, getCurrentInstance, reactive, ref, toRefs} from "vue";
import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import axios from "axios";
import showdown from "showdown";
import {
  addArticle,
  delArticle,
  getArticle,
  getDicts,
  listArticle, pubOrShelf,
  randomImgMethod,
  updateArticle
} from "@/api/blog/article";
import {QuestionFilled} from "@element-plus/icons-vue";
import {ElLoading} from "element-plus";
import {fetchCategory} from "@/api/blog/category";
import {marked} from "marked";

const text = ref('Hello Editor!');
const {proxy} = getCurrentInstance();
const tagsList = ref([]);
const open = ref(false);
const loading = ref(true);
const loadingBox = ref(null);
const showSearch = ref(true);
const ids = ref([]);
const titles = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const formLabelWidth = ref("120px");
const publishList = ref([]);
const readTypeList = ref(["无需验证", "评论阅读", "点赞阅读", "扫码阅读"]);
const isOriginalList = ref(["转载", "原创"]);
const yesOrNoList = ref(["否", "是"]);
const yesOrNoStyle = ref(['danger', 'success']);
const readTypeStyle = ref(['', 'info', 'warning', 'success']);
const category = ref([]);
const visible = ref(false);
const files = ref({});
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload");
const tagName = ref(null);
const categoryName = ref(null);
const tags = ref([]);
const fullscreenFlag = ref(true);
const isTagsValid = computed(() => {
  return form.tags && form.tags.length < 3;
});
const isCategoryValid = computed(() => {
  return form.categoryName && form.categoryName.length >= 1
  console.log("========="+form.categoryName && form.categoryName.length >= 1)
});

const tagClass = () => {
  return function (item) {
    const index = form.value.tags.indexOf(item.name);
    return index !== -1 ? "tag-item-select" : "tag-item";
  };
}
const openLoading = () => {
  loadingBox.value = ElLoading.service({
    lock: true,
    text: '正在加载中~',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
const closeLoading = () => {
  loadingBox.value.close();
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    tagId: null,
    categoryId: null,
    isPublish: null,
  },
  rules:
      {
        'title': [{ required: true, message: '必填字段', trigger: 'blur' }],
        'summary': [{ required: true, message: '必填字段', trigger: 'blur' }],
        'tags': [{ required: true, message: '必填字段', trigger: 'blur' }],
        'categoryName': [{ required: true, message: '必填字段', trigger: 'blur' }],
        'readType': [{ required: true, message: '必填字段', trigger: 'change' }],
        'isStick': [{ required: true, message: '必填字段', trigger: 'change' }],
        'isPublish': [{ required: true, message: '必填字段', trigger: 'change' }],
        'isOriginal': [{ required: true, message: '必填字段', trigger: 'change' }],
        'originalUrl': [{ required: true, message: '必填字段', trigger: 'blur' }],
        'contentMd': [{ required: true, message: '必填字段', trigger: 'change' }],
        'isRecommend': [{ required: true, message: '必填字段', trigger: 'change' }],
        'isCarousel': [{ required: true, message: '必填字段', trigger: 'change' }]
      }
});

const {queryParams, form, rules} = toRefs(data);

// 图片上传事件
const onUploadImg = async (files, callback) => {
  console.log("in")
  const res = await Promise.all(
      files.map((file) => {
        return new Promise((rev, rej) => {
          // 传给后端一个FormData数据，添加键值对，这里我添加了这个文章的ID和file
          const form = new FormData();
          form.append('file', file);
          form.append("articleId", 5)
          // 这里是我的后端接口，请求地址和路径可以自己改
          axios.post('http://localhost:8082/work/uploadImg', form, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
              .then((res) => {
                console.log(res)
                rev(res)
              })
              .catch((error) => rej(error));
        });
      })
  );
  callback(res.map((item) => item.data.url));
};

/** 查询公告列表 */
function getList() {
  loading.value = true;
  listArticle(queryParams.value).then(response => {
    tagsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getTagsList() {
  listNoPage().then(response => {
    tags.value = response.data;
    console.log(tags.value);
  });
}
function strSplit(item) {
  return item.split(",")
}
function offShelf(scope) {
  let article = { id: scope.row.id, isPublish: 0 }
  pubOrShelf(article).then(res => {
    proxy.$modal.msgSuccess("下架文章成功");
    getList();
  }).catch(err => {
    console.log(err)
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    title: '',
    avatar: '',
    summary: '',
    quantity: 0,
    content: '',
    contentMd: '',
    isSecret: 0,
    isStick: 0,
    isOriginal: 1,
    isCarousel: 0,
    isRecommend: 0,
    remark: '',
    keywords: '',
    categoryName: null,
    isPublish: 1,
    readType: '',
    tags: []
  };
  proxy.resetForm("tagRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  titles.value = selection.map(item => item.title);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增文章";
}

/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;

  getArticle(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文章";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dataForm"].validate(valid => {
    if (valid) {
      const html = marked(form.value.contentMd);
      form.value.content = html;
      if (form.value.id != undefined) {
        updateArticle(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addArticle(form.value).then(response => {
          proxy.$modal.msgSuccess("添加文章成功");
          open.value = false;
          getList();
        });
      }
    }else {
      proxy.$modal.msgError("存在必填字段未填");
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value
  const name = row.title || titles.value
  proxy.$modal.confirm('是否确认删除文章名为"' + name + '"的数据项？').then(function () {
    return delArticle(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("articles/tags/export", {
    ...queryParams.value
  }, `tags_${new Date().getTime()}.xlsx`);
}

function imgAdd(pos, $file) {
  var formdata = new FormData();
  // formdata.append('multipartFile', $file);
  // upload(formdata).then(res => {
  //   this.$refs.md.$img2Url(pos, res.data);
  // }).catch(err => {
  //   console.log(err)
  // })
}

function imgDel(filename) {
  // delBatchFile(filename[0].split(this.img)[1])
}

function getDictList() {
  let dictTypes = ['sys_publish_status'];
  getDicts(dictTypes).then(response => {
    let dictMap = response.data;
    // this.dictYesOrNoList = dictMap.sys_yes_no.list
    // this.yesOrNoDefaultValue = dictMap.sys_yes_no.defaultValue
    publishList.value = dictMap;
    // console.log('publishList',publishList)
  }).catch(err => {
    console.error(err)
  })
}

function getCategoryList() {
  fetchCategory().then(res => {
    category.value = res.data;
    console.log(category.value);
  })
}

function randomImg() {
  openLoading();
  handleDeletePic();
  randomImgMethod().then(res => {
    form.value.avatar = res.data;
    visible.value = false
    closeLoading();
  }).catch(err => {
    console.error(err)
    closeLoading();
  });

}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    form.value.avatar = res.url;
  }
}

function handleDeletePic(res, file) {
  form.value.avatar = null;
}

function removeTag(item) {
  const index = form.value.tags.indexOf(item);
  form.value.tags.splice(index, 1);
}

function addTag(item) {
  if (form.value.tags.length > 2) {
    proxy.$modal.msgError("最多添加三个标签,如需继续添加,请先删除一个!");
    return false;
  }
  if (form.value.tags.indexOf(item.name) === -1) {
    form.value.tags.push(item.name);
  }
};

function saveTag() {
  if (tagName.value.trim() !== "") {
    addTag({
      name: tagName.value
    });
    tagName.value = "";
  }
};

function addCategoryMethod(item) {
  form.value.categoryName = item.name
}

function saveCategory() {
  if (categoryName.value.trim() !== "") {
    form.value.categoryName = categoryName.value
  }
}

function removeCategory() {
  form.value.categoryName = null
}

getDictList();
getTagsList();
getCategoryList();
getList();
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 200px;
  height: 110px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 110px;
  text-align: center;
}

.icon-style {
  top: -42px;
  left: -5px;
}
#imgIcon {
  color: #fff;
  font-size: 1.5rem;
  position: absolute;
  top: 1rem;
  left: 1rem;
  bottom: 1.4rem;
}
</style>
